﻿using System;
using System.Collections.Generic;
using System.Text;
using SHDocVw;
using mshtml;
using System.Windows.Forms;

namespace AppleAutoBuy.Common
{
     public class AppleBrowserOperator
     {
         #region Const
         public const int MaxCount = 1000;
         public const int Interval = 5;
         #endregion
         #region Ctor

         public AppleBrowserOperator()
         { 
         }

         #endregion

         #region Properties

         public InternetExplorer IE
         {
             get;
             private set;
         }

         #endregion

         public void Start(string url, string postData)
         {
             IE = Util.OpenNewIe(url, postData);
             
             IHTMLDocument2 doc21 = Util.GetIDoc2FromTitle("Apple - 预订和取货", out docHwnd);
             IE.NavigateError += new DWebBrowserEvents2_NavigateErrorEventHandler(IE_NavigateError);
             IE.ThirdPartyUrlBlocked += new DWebBrowserEvents2_ThirdPartyUrlBlockedEventHandler(IE_ThirdPartyUrlBlocked);
             IE.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(IE_DocumentComplete);

         }

         IntPtr docHwnd = IntPtr.Zero;

         #region Events

         void IE_DocumentComplete(object pDisp, ref object URL)
         { 
             string url = (string)URL;
             IHTMLDocument doc = (IHTMLDocument)IE.Document; 
             IHTMLDocument3 doc3 = (IHTMLDocument3)doc;
             HTMLDocumentClass docClass = (HTMLDocumentClass )doc;
              

             //IntPtr hwnd = IntPtr.Zero;
             string title = ((IHTMLDocument2)IE.Document).title;
             IHTMLDocument2 doc2 = Util.GetIDoc2FromHandle(docHwnd);

             IWebBrowser webBrowser = (IWebBrowser)IE; 
             if (doc != null && String.Equals(url,ResourceManager.AppleData.StartUrl, StringComparison.CurrentCultureIgnoreCase))
             {
                 AppleAction checkStore = CheckStore;
                 checkStore.BeginInvoke(doc, new AsyncCallback(result => {
                     if (result.IsCompleted)
                     {
                         IHTMLDocument2 d2 = (IHTMLDocument2)doc;
                         IHTMLDocument2 doc21 = Util.GetIDoc2FromTitle(d2.title, out docHwnd);
                         bool isChecked = checkStore.EndInvoke(result);
                         if (isChecked)
                         {
                             IHTMLElement element = doc3.getElementById("storePopUpButton.ID148");
                             IHTMLSelectElement select = (IHTMLSelectElement)element;
                              

                             Util.SetState(VirtualKeys.VK_DOWN, true);
                             //Util.SetState(VirtualKeys.VK_DOWN, false);
                             //Util.SetState(VirtualKeys.VK_DOWN, true);

                             AppleAction confirmStore = ConfirmStore;
                             confirmStore.BeginInvoke(doc, new AsyncCallback(cresult => {
                                 if (cresult.IsCompleted)
                                 {
                                     bool isConfirmed = confirmStore.EndInvoke(cresult);
                                 }
                             }), null);
                         }
                     }
                 }), null);                
             }
         }

         void IE_ThirdPartyUrlBlocked(ref object URL, uint dwCount)
         {
         }

         void IE_NavigateError(object pDisp, ref object URL, ref object Frame, ref object StatusCode, ref bool Cancel)
         {
         }

         #endregion

         public delegate bool AppleAction(IHTMLDocument doc );

         public bool CheckStore(IHTMLDocument doc )
         {
             HTMLDocumentClass docClass = (HTMLDocumentClass)doc;
             HTMLScriptElementClass scriptEle = (HTMLScriptElementClass)docClass.createElement("script");
            
            
             //scriptEle.setAttribute("type", "javascript/text");
             //docClass.appendChild(scriptEle);

              
             scriptEle.type = "JavaScript";
             //scriptEle.insertAdjacentHTML("", "alert(1)");
             //scriptEle.innerHTML = "alert(1)";
             //docClass.appendChild(scriptEle);
             //docClass.insertBefore((IHTMLDOMNode)scriptEle);
             IHTMLDocument2 doc2 =(IHTMLDocument2)doc;
             
             IHTMLDocument3 doc3 = (IHTMLDocument3)doc;
             bool result = false;
             int i = 0;
             while (i < MaxCount)
             {
                 IHTMLElement element = doc3.getElementById("storePopUpButton.ID148");
                 if (element != null)
                 {                     
                     IHTMLSelectElement select = (IHTMLSelectElement)element;
                     IHTMLElement item = (IHTMLElement)select.item(3);
                     if (item != null)
                     { 
                         IHTMLOptionElement dd = (IHTMLOptionElement)item; 
                         try
                         {
                             //element.click();
                             select.selectedIndex = 3;
                             ((IHTMLElement2)element).setCapture(true);
                             ((IHTMLElement3)element).FireEvent("onmousedown");
                             

                             ////Util.SetState(VirtualKeys.VK_DOWN, true);
                             ////Util.SetState(VirtualKeys.VK_DOWN, false);
                             ////Util.SetState(VirtualKeys.VK_DOWN, true);
                             ////Util.SetState(VirtualKeys.VK_DOWN, false);
                             ////Util.SetState(VirtualKeys.VK_DOWN, true);
                             ////element.click();
                             result = true;
                             break;
                         }
                         catch(Exception e) { 
                         }
                     }
                 }
                 i++;
             }

             return result;
         }

         public bool ConfirmStore(IHTMLDocument doc )
         {
             IHTMLDocument3 doc3 = (IHTMLDocument3)doc;
             bool result = false;
             int i = 0;
             while (i < MaxCount)
             {
                 IHTMLElement element = doc3.getElementById("fwdButtonC.ID152"); 
                 if (element != null)
                 {
                     IHTMLAnchorElement anchor = (IHTMLAnchorElement)element;
                     if (anchor != null)
                     {
                         try
                         {                         
                             anchor.focus();                            
                             element.click();
                             //Util.SetState(VirtualKeys.VK_LBUTTON, true);
                             //Util.mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
                             result = true;
                             break;
                         }
                         catch (Exception e)
                         {
                         }
                     }
                 }
                 i++;
             }

             return result;
         }

    }
}
